package _05thread;

/**
 * @description:
 * @author: 景天
 * @date: 2022/2/11 11:31
 **/

import java.io.*;

/**
 * @description:
 * @author: songtao@cskaoyan.onaliyun.com
 **/

/*
使用多线程实现方式二 ,多个文件一起复制功能，
并在控制台显示复制的进度，进度以百分比表示

例如：把文件A复制到E盘某文件夹下，在控制台上显示“XXX文件已复制xx%”，
“XXX文件已复制xxx%”……“XXX文件已复制xxx%”，“XXX复制完成！
 */
public class Work4 {
    public static void main(String[] args) {

        new Thread(new CopyFileRunnable("D:\\temp\\aa.jpg", "aa.jpg")).start();
        new Thread(new CopyFileRunnable("D:\\temp\\bb.jpg", "bb.jpg")).start();
        new Thread(new CopyFileRunnable("D:\\temp\\cc.jpg", "cc.jpg")).start();
    }
}

class CopyFileRunnable implements Runnable{
    File oldFile;
    File newFile;

    public CopyFileRunnable(String oldFile, String newFile) {
        this.oldFile = new File(oldFile);
        this.newFile = new File(newFile);
    }
    @Override
    public void run() {
        // 复制文件操作
        try(FileInputStream in = new FileInputStream(oldFile);
            FileOutputStream out = new FileOutputStream(newFile)) {

            // 边读边写
            int readCount;

            byte[] bytes = new byte[1024];
            // 用来做累加的
            double temp = 0;
            long length = oldFile.length();
            while ((readCount = in.read(bytes)) != -1) {
                // write
                out.write(bytes);
                temp += readCount;
                double persent = temp / length * 100;
                System.out.println(oldFile + "复制了:"+String.format("%.2f",persent)+"%");
            }
            System.out.println(oldFile + "复制完成!");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}